// src/api/index.js
import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
api.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        console.error('API Error:', error)
        const status = error?.response?.status
        if (status === 401) {
            // 未认证或 token 失效：清理本地状态并跳转登录
            try {
                localStorage.removeItem('token')
                localStorage.removeItem('userInfo')
            } catch {}
            const redirect = encodeURIComponent(window.location.pathname + window.location.search)
            if (!window.location.pathname.startsWith('/login')) {
                window.location.href = `/login?redirect=${redirect}`
            }
        }
        return Promise.reject(error)
    }
)

// 项目相关 API
export const projectApi = {
    // 获取项目列表
    getProjects: (params) => api.get('/projects', { params }),

    // 获取项目详情
    getProject: (id) => api.get(`/projects/${id}`),

    // 创建项目
    createProject: (data) => api.post('/projects', data),

    // 更新项目
    updateProject: (id, data) => api.put(`/projects/${id}`, data),

    // 删除项目
    deleteProject: (id) => api.delete(`/projects/${id}`),

    // 审核项目
    auditProject: (id, data) => api.post(`/projects/${id}/audit`, data)
}

// 文件上传 API
export const uploadApi = {
    // 上传文件
    uploadFile: (file, onProgress) => {
        const formData = new FormData()
        formData.append('file', file)

        return api.post('/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: onProgress
        })
    },

    // 删除文件
    deleteFile: (fileId) => api.delete(`/files/${fileId}`)
}

// 用户认证 API
export const authApi = {
    // 登录
    login: (credentials) => api.post('/auth/login', credentials),

    // 退出
    logout: () => api.post('/auth/logout'),

    // 获取用户信息
    getUserInfo: () => api.get('/auth/me')
}

export default api